<script setup lang="ts">
import type { Address } from '@/types/mall'
import { formatTime } from '@/utils/mall'

const userStore = useUserStore()
const router = useRouter()

// 地址列表
const addresses = ref<Address[]>([])
const loading = ref(false)

// 模拟地址数据
const mockAddresses: Address[] = [
  {
    id: '1',
    userId: '1',
    name: '张三',
    phone: '13800138000',
    province: '广东省',
    city: '深圳市',
    district: '南山区',
    detail: '科技园南区深圳湾科技生态园10栋A座',
    postalCode: '518000',
    isDefault: true,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    userId: '1',
    name: '李四',
    phone: '13900139000',
    province: '广东省',
    city: '广州市',
    district: '天河区',
    detail: '珠江新城CBD中心区天河路123号',
    isDefault: false,
    createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    userId: '1',
    name: '王五',
    phone: '13700137000',
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    detail: '建国门外大街1号国贸大厦',
    isDefault: false,
    createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString(),
  },
]

// 获取地址列表
async function getAddressList() {
  try {
    loading.value = true
    
    // TODO: 调用API获取地址列表
    // const response = await api.address.getAddressList()
    // addresses.value = response.data
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    addresses.value = mockAddresses
  } catch (error) {
    console.error('获取地址列表失败:', error)
    uni.showToast({ title: '获取地址失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 设置默认地址
async function setDefaultAddress(addressId: string) {
  try {
    // TODO: 调用API设置默认地址
    // await api.address.setDefaultAddress(addressId)
    
    // 更新本地数据
    addresses.value.forEach(addr => {
      addr.isDefault = addr.id === addressId
    })
    
    uni.showToast({ title: '设置成功', icon: 'success' })
  } catch (error) {
    console.error('设置默认地址失败:', error)
    uni.showToast({ title: '设置失败', icon: 'none' })
  }
}

// 删除地址
function deleteAddress(addressId: string) {
  uni.showModal({
    title: '删除地址',
    content: '确定要删除这个地址吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用API删除地址
          // await api.address.deleteAddress(addressId)
          
          // 更新本地数据
          const index = addresses.value.findIndex(addr => addr.id === addressId)
          if (index > -1) {
            addresses.value.splice(index, 1)
          }
          
          uni.showToast({ title: '删除成功', icon: 'success' })
        } catch (error) {
          console.error('删除地址失败:', error)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

// 编辑地址
function editAddress(addressId: string) {
  uni.navigateTo({ url: `/subPackages/user-package/address/edit?id=${addressId}` })
}

// 添加新地址
function addNewAddress() {
  uni.navigateTo({ url: '/subPackages/user-package/address/edit' })
}

// 格式化地址显示
function formatAddress(address: Address): string {
  return `${address.province}${address.city}${address.district}${address.detail}`
}

// 页面生命周期
onMounted(() => {
  getAddressList()
})
</script>

<template>
  <view class="address-list-page">
    <!-- 地址列表 -->
    <view v-if="loading" class="loading-container">
      <wd-loading size="24px" />
      <text>加载中...</text>
    </view>

    <view v-else-if="addresses.length === 0" class="empty-state">
      <wd-icon name="location" size="60px" color="#ddd" />
      <text class="empty-text">暂无收货地址</text>
      <wd-button type="primary" size="large" @click="addNewAddress">
        添加新地址
      </wd-button>
    </view>

    <view v-else class="address-list">
      <view
        v-for="address in addresses"
        :key="address.id"
        class="address-item"
      >
        <!-- 默认标签 -->
        <view v-if="address.isDefault" class="default-tag">
          默认
        </view>

        <!-- 地址信息 -->
        <view class="address-info">
          <view class="contact-info">
            <text class="name">{{ address.name }}</text>
            <text class="phone">{{ address.phone }}</text>
          </view>
          
          <text class="address-detail">
            {{ formatAddress(address) }}
          </text>
          
          <text v-if="address.postalCode" class="postal-code">
            邮编：{{ address.postalCode }}
          </text>
        </view>

        <!-- 操作按钮 -->
        <view class="address-actions">
          <wd-button
            v-if="!address.isDefault"
            type="info"
            size="small"
            @click="setDefaultAddress(address.id)"
          >
            设为默认
          </wd-button>
          
          <wd-button
            type="primary"
            size="small"
            @click="editAddress(address.id)"
          >
            编辑
          </wd-button>
          
          <wd-button
            type="error"
            size="small"
            @click="deleteAddress(address.id)"
          >
            删除
          </wd-button>
        </view>
      </view>
    </view>

    <!-- 添加新地址按钮 -->
    <view class="add-address-btn">
      <wd-button
        type="primary"
        size="large"
        block
        @click="addNewAddress"
      >
        <wd-icon name="plus" size="16px" />
        添加新地址
      </wd-button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.address-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;

  .empty-text {
    margin: 20px 0 30px;
    font-size: 16px;
    color: #999;
  }
}

.address-list {
  padding: 15px;

  .address-item {
    position: relative;
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .default-tag {
      position: absolute;
      top: 15px;
      right: 15px;
      background: #ff4142;
      color: white;
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 10px;
    }

    .address-info {
      margin-bottom: 15px;

      .contact-info {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 10px;

        .name {
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }

        .phone {
          font-size: 14px;
          color: #666;
        }
      }

      .address-detail {
        display: block;
        font-size: 14px;
        color: #333;
        line-height: 1.5;
        margin-bottom: 8px;
      }

      .postal-code {
        font-size: 12px;
        color: #999;
      }
    }

    .address-actions {
      display: flex;
      gap: 10px;

      :deep(.wd-button) {
        flex: 1;
      }
    }
  }
}

.add-address-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  border-top: 1px solid #f0f0f0;

  :deep(.wd-button) {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }
}
</style>

<route lang="json">
{
  "name": "addressList",
  "style": {
    "navigationBarTitleText": "收货地址"
  }
}
</route>